package com.snow.dayou.aop;

import com.snow.common.base.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.UUID;

/**
 * All rights Reserved, Designed By www.cusc.com
 *
 * @author yanke
 * @Title: RequestIdAop
 * @Package com.snow.dayou.aop
 * @Description:类描述
 * @Email yanke@cu-sc.com
 * @version: v1.0.0
 * @date: 2021/5/20/0020 13:39
 * @Copyright: 2021  www.faw.com.cn Inc. All rights reserved. <br/>
 * Modification History:<br/>
 * Date         Author          Version            Description<br/>
 * *---------------------------------------------------------*<br/>
 * 2021/5/20/0020     Administrator           v1.0.0               修改原因<br/>
 * @since JDK 1.8
 */
@Order(Ordered.LOWEST_PRECEDENCE)
@Component
@Aspect
@Slf4j
public class RequestIdAop {

    @Before("execution (* com.snow.dayou.controller..*.*(..))")
    public void RequestIdAopBefore() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String requestid = request.getHeader(CommonConstant.REQUESTID);
        if (Objects.nonNull(requestid)) {
            MDC.put(CommonConstant.REQUESTID, requestid);
        } else {
            MDC.put(CommonConstant.REQUESTID, UUID.randomUUID().toString());
        }
        log.info(MDC.get(CommonConstant.REQUESTID));
    }

    @After("execution (* com.snow.dayou.controller..*.*(..))")
    public void RequestIdAopAfter() {
        String requestId = MDC.get(CommonConstant.REQUESTID);
        log.info(requestId);
        if (Objects.nonNull(requestId)) {
            MDC.remove(CommonConstant.REQUESTID);
        }
    }

    @Before("execution (* com.snow.dayou.service..*.*(..))")
    public void ServiceAopBefore() {
        String mqMsgId = MDC.get(CommonConstant.MQMSGID);
        String requestId = MDC.get(CommonConstant.REQUESTID);
        if (Objects.isNull(requestId) && Objects.isNull(mqMsgId)) {
            MDC.put(CommonConstant.REQUESTID, UUID.randomUUID().toString());
        }
    }

    @After("execution (* com.snow.dayou.service..*.*(..))")
    public void ServiceAopAfter() {
        String mqMsgId = MDC.get(CommonConstant.MQMSGID);
        if (Objects.nonNull(mqMsgId)) {
            MDC.remove(CommonConstant.MQMSGID);
        }
    }
}
